This repository has been archived by the owner on May 10, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 441
/
PlaylistManager.swift
812 lines (688 loc) · 25.8 KB
/
PlaylistManager.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// Copyright 2020 The Brave Authors. All rights reserved.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import Foundation
import AVFoundation
import Combine
import CoreData
import Shared
import Data
import Preferences
import os.log
public class PlaylistManager: NSObject {
public static let shared = PlaylistManager()
private var assetInformation = [PlaylistAssetFetcher]()
private let downloadManager = PlaylistDownloadManager()
private var frc = PlaylistItem.frc()
private var didRestoreSession = false
private var _playbackTask: Task<Void, Error>?
var playbackTask: Task<Void, Error>? {
get {
_playbackTask
}
set(newValue) {
_playbackTask?.cancel()
_playbackTask = newValue
}
}
// Observers
private let onContentWillChange = PassthroughSubject<Void, Never>()
private let onContentDidChange = PassthroughSubject<Void, Never>()
private let onObjectChange = PassthroughSubject<
(
object: Any,
indexPath: IndexPath?,
type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?
), Never
>()
private let onDownloadProgressUpdate = PassthroughSubject<
(
id: String,
percentComplete: Double
), Never
>()
private let onDownloadStateChanged = PassthroughSubject<
(
id: String,
state: PlaylistDownloadManager.DownloadState,
displayName: String?,
error: Error?
), Never
>()
private let onCurrentFolderChanged = PassthroughSubject<(), Never>()
private let onFolderDeleted = PassthroughSubject<(), Never>()
private override init() {
super.init()
downloadManager.delegate = self
frc.delegate = self
// Delete system cache always on startup.
deleteUserManagedAssets()
}
var currentFolder: PlaylistFolder? {
didSet {
frc.delegate = nil
if let currentFolder = currentFolder {
// Only return an FRC for the specified folder
frc = PlaylistItem.frc(parentFolder: currentFolder)
} else {
// Return every folder, including the "Saved" folder
frc = PlaylistItem.allFoldersFRC()
}
frc.delegate = self
reloadData()
onCurrentFolderChanged.send()
}
}
var onFolderRemovedOrUpdated: AnyPublisher<Void, Never> {
onFolderDeleted.eraseToAnyPublisher()
}
var contentWillChange: AnyPublisher<Void, Never> {
onContentWillChange.eraseToAnyPublisher()
}
var contentDidChange: AnyPublisher<Void, Never> {
onContentDidChange.eraseToAnyPublisher()
}
var objectDidChange: AnyPublisher<(object: Any, indexPath: IndexPath?, type: NSFetchedResultsChangeType, newIndexPath: IndexPath?), Never> {
onObjectChange.eraseToAnyPublisher()
}
var downloadProgressUpdated: AnyPublisher<(id: String, percentComplete: Double), Never> {
onDownloadProgressUpdate.eraseToAnyPublisher()
}
var downloadStateChanged: AnyPublisher<(id: String, state: PlaylistDownloadManager.DownloadState, displayName: String?, error: Error?), Never> {
onDownloadStateChanged.eraseToAnyPublisher()
}
var onCurrentFolderDidChange: AnyPublisher<(), Never> {
onCurrentFolderChanged.eraseToAnyPublisher()
}
var allItems: [PlaylistInfo] {
frc.fetchedObjects?.map({ PlaylistInfo(item: $0) }) ?? []
}
var numberOfAssets: Int {
frc.fetchedObjects?.count ?? 0
}
var fetchedObjects: [PlaylistItem] {
frc.fetchedObjects ?? []
}
func updateLastPlayed(item: PlaylistInfo, playTime: Double) {
let lastPlayedTime = Preferences.Playlist.playbackLeftOff.value ? playTime : 0.0
Preferences.Playlist.lastPlayedItemUrl.value = item.pageSrc
PlaylistItem.updateLastPlayed(itemId: item.tagId, pageSrc: item.pageSrc, lastPlayedOffset: lastPlayedTime)
}
func itemAtIndex(_ index: Int) -> PlaylistInfo? {
if index >= 0 && index < numberOfAssets {
return PlaylistInfo(item: frc.object(at: IndexPath(row: index, section: 0)))
}
return nil
}
func assetAtIndex(_ index: Int) -> AVURLAsset? {
if let item = itemAtIndex(index) {
return asset(for: item.tagId, mediaSrc: item.src)
}
return nil
}
func index(of itemId: String) -> Int? {
frc.fetchedObjects?.firstIndex(where: { $0.uuid == itemId })
}
func reorderItems(from sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath, completion: (() -> Void)?) {
guard var objects = frc.fetchedObjects else {
ensureMainThread {
completion?()
}
return
}
frc.managedObjectContext.perform { [weak self] in
defer {
ensureMainThread {
completion?()
}
}
guard let self = self else { return }
let src = self.frc.object(at: sourceIndexPath)
objects.remove(at: sourceIndexPath.row)
objects.insert(src, at: destinationIndexPath.row)
for (order, item) in objects.enumerated().reversed() {
item.order = Int32(order)
}
do {
try self.frc.managedObjectContext.save()
} catch {
Logger.module.error("\(error.localizedDescription)")
}
}
}
func state(for itemId: String) -> PlaylistDownloadManager.DownloadState {
if downloadManager.downloadTask(for: itemId) != nil {
return .inProgress
}
if let assetUrl = downloadManager.localAsset(for: itemId)?.url {
if FileManager.default.fileExists(atPath: assetUrl.path) {
return .downloaded
}
}
return .invalid
}
func sizeOfDownloadedItem(for itemId: String) -> String? {
var isDirectory: ObjCBool = false
if let asset = downloadManager.localAsset(for: itemId),
FileManager.default.fileExists(atPath: asset.url.path, isDirectory: &isDirectory) {
let formatter = ByteCountFormatter().then {
$0.zeroPadsFractionDigits = true
$0.countStyle = .file
}
if isDirectory.boolValue || asset.url.pathExtension.lowercased() == "movpkg" {
let properties: [URLResourceKey] = [.isRegularFileKey, .totalFileAllocatedSizeKey]
guard
let enumerator = FileManager.default.enumerator(
at: asset.url,
includingPropertiesForKeys: properties,
options: .skipsHiddenFiles,
errorHandler: nil)
else {
return nil
}
let sizes = enumerator.compactMap({
try? ($0 as? URL)?
.resourceValues(forKeys: Set(properties))
})
.filter({ $0.isRegularFile == true })
.compactMap({ $0.totalFileAllocatedSize })
.compactMap({ Int64($0) })
return formatter.string(fromByteCount: Int64(sizes.reduce(0, +)))
}
if let size = try? FileManager.default.attributesOfItem(atPath: asset.url.path)[.size] as? Int {
return formatter.string(fromByteCount: Int64(size))
}
}
return nil
}
func reloadData() {
do {
try frc.performFetch()
} catch {
Logger.module.error("\(error.localizedDescription)")
}
}
public func restoreSession() {
if !didRestoreSession {
downloadManager.restoreSession() { [weak self] in
self?.reloadData()
}
}
}
public func setupPlaylistFolder() {
if let savedFolder = PlaylistFolder.getFolder(uuid: PlaylistFolder.savedFolderUUID) {
if savedFolder.title != Strings.PlaylistFolders.playlistSavedFolderTitle {
// This title may change so we should update it
savedFolder.title = Strings.PlaylistFolders.playlistSavedFolderTitle
}
} else {
PlaylistFolder.addFolder(title: Strings.PlaylistFolders.playlistSavedFolderTitle, uuid: PlaylistFolder.savedFolderUUID) { uuid in
Logger.module.debug("Created Playlist Folder: \(uuid)")
}
}
}
func download(item: PlaylistInfo) {
guard downloadManager.downloadTask(for: item.tagId) == nil, let assetUrl = URL(string: item.src) else { return }
Task {
let mimeType = await PlaylistMediaStreamer.getMimeType(assetUrl)
guard let mimeType = mimeType?.lowercased() else { return }
if mimeType.contains("x-mpegurl") || mimeType.contains("application/vnd.apple.mpegurl") || mimeType.contains("mpegurl") {
DispatchQueue.main.async {
self.downloadManager.downloadHLSAsset(assetUrl, for: item)
}
} else {
DispatchQueue.main.async {
self.downloadManager.downloadFileAsset(assetUrl, for: item)
}
}
}
}
func cancelDownload(itemId: String) {
downloadManager.cancelDownload(itemId: itemId)
}
func delete(folder: PlaylistFolder, _ completion: ((_ success: Bool) -> Void)? = nil) {
var success = true
var itemsToDelete = [PlaylistInfo]()
folder.playlistItems?.forEach({
let item = PlaylistInfo(item: $0)
cancelDownload(itemId: item.tagId)
if let index = assetInformation.firstIndex(where: { $0.itemId == item.tagId }) {
let assetFetcher = self.assetInformation.remove(at: index)
assetFetcher.cancelLoading()
}
if !deleteCache(item: item) {
// If we cannot delete an item's cache for any given reason,
// Do NOT delete the folder containing the item.
// Delete all other items.
success = false
} else {
itemsToDelete.append(item)
}
})
if success, currentFolder?.objectID == folder.objectID {
currentFolder = nil
}
// Delete items from the folder
PlaylistItem.removeItems(itemsToDelete) {
// Attempt to delete the folder if we can
if success, folder.uuid != PlaylistFolder.savedFolderUUID {
PlaylistFolder.removeFolder(folder.uuid ?? "") { [weak self] in
guard let self = self else {
completion?(success)
return
}
if self.currentFolder?.isDeleted == true {
self.currentFolder = nil
}
self.onFolderDeleted.send()
self.reloadData()
completion?(success)
}
} else {
if self.currentFolder?.isDeleted == true {
self.currentFolder = nil
}
self.onFolderDeleted.send()
self.reloadData()
completion?(success)
}
}
}
@discardableResult
func delete(item: PlaylistInfo) -> Bool {
cancelDownload(itemId: item.tagId)
if let index = assetInformation.firstIndex(where: { $0.itemId == item.tagId }) {
let assetFetcher = self.assetInformation.remove(at: index)
assetFetcher.cancelLoading()
}
if let cacheItem = PlaylistItem.getItem(uuid: item.tagId),
cacheItem.cachedData != nil {
// Do NOT delete the item if we can't delete it's local cache.
// That will cause zombie items.
if deleteCache(item: item) {
PlaylistItem.removeItems([item])
onDownloadStateChanged(id: item.tagId, state: .invalid, displayName: nil, error: nil)
return true
}
return false
} else {
PlaylistItem.removeItems([item])
onDownloadStateChanged(id: item.tagId, state: .invalid, displayName: nil, error: nil)
return true
}
}
@discardableResult
func deleteCache(item: PlaylistInfo) -> Bool {
cancelDownload(itemId: item.tagId)
if let cacheItem = PlaylistItem.getItem(uuid: item.tagId),
let cachedData = cacheItem.cachedData,
!cachedData.isEmpty {
var isStale = false
do {
let url = try URL(resolvingBookmarkData: cachedData, bookmarkDataIsStale: &isStale)
if FileManager.default.fileExists(atPath: url.path) {
try FileManager.default.removeItem(atPath: url.path)
PlaylistItem.updateCache(uuid: item.tagId, cachedData: nil)
onDownloadStateChanged(id: item.tagId, state: .invalid, displayName: nil, error: nil)
}
return true
} catch {
Logger.module.error("An error occured deleting Playlist Cached Item \(cacheItem.name ?? item.tagId): \(error.localizedDescription)")
return false
}
}
return true
}
func deleteAllItems(cacheOnly: Bool) {
// This is the only way to have the system kill picture in picture as the restoration controller is deallocated
// And that means the video is deallocated, its AudioSession is stopped, and the Picture-In-Picture controller is deallocated.
// This is because `AVPictureInPictureController` is NOT a view controller and there is no way to dismiss it
// other than to deallocate the restoration controller.
// We could also call `AVPictureInPictureController.stopPictureInPicture` BUT we'd still have to deallocate all resources.
// At least this way, we deallocate both AND pip is stopped in the destructor of `PlaylistViewController->ListController`
PlaylistCarplayManager.shared.playlistController = nil
guard let playlistItems = frc.fetchedObjects else {
Logger.module.error("An error occured while fetching Playlist Objects")
return
}
for item in playlistItems {
let item = PlaylistInfo(item: item)
if !deleteCache(item: item) {
continue
}
if !cacheOnly {
PlaylistItem.removeItems([item])
}
}
if !cacheOnly {
assetInformation.forEach({ $0.cancelLoading() })
assetInformation.removeAll()
}
// Delete playlist directory.
// Though it should already be empty
if let playlistDirectory = PlaylistDownloadManager.playlistDirectory {
do {
try FileManager.default.removeItem(at: playlistDirectory)
} catch {
Logger.module.error("Failed to delete Playlist Directory: \(error.localizedDescription)")
}
}
// Delete system cache
deleteUserManagedAssets()
}
private func deleteUserManagedAssets() {
// Cleanup System Cache Folder com.apple.UserManagedAssets*
if let libraryPath = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first {
do {
let urls = try FileManager.default.contentsOfDirectory(
at: libraryPath,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles])
for url in urls where url.absoluteString.contains("com.apple.UserManagedAssets") {
do {
let assets = try FileManager.default.contentsOfDirectory(
at: url,
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles])
assets.forEach({
if let item = PlaylistItem.cachedItem(cacheURL: $0), let itemId = item.uuid {
self.cancelDownload(itemId: itemId)
PlaylistItem.updateCache(uuid: itemId, cachedData: nil)
}
})
} catch {
Logger.module.error("Failed to update Playlist item cached state: \(error.localizedDescription)")
}
do {
try FileManager.default.removeItem(at: url)
} catch {
Logger.module.error("Deleting Playlist Item for \(url.absoluteString) failed: \(error.localizedDescription)")
}
}
} catch {
Logger.module.error("Deleting Playlist Incomplete Items failed: \(error.localizedDescription)")
}
}
}
func autoDownload(item: PlaylistInfo) {
guard let downloadType = PlayListDownloadType(rawValue: Preferences.Playlist.autoDownloadVideo.value) else {
return
}
switch downloadType {
case .on:
PlaylistManager.shared.download(item: item)
case .wifi:
if DeviceInfo.hasWifiConnection() {
PlaylistManager.shared.download(item: item)
}
case .off:
break
}
}
func isDiskSpaceEncumbered() -> Bool {
let freeSpace = availableDiskSpace() ?? 0
let totalSpace = totalDiskSpace() ?? 0
let usedSpace = totalSpace - freeSpace
// If disk space is 90% used
return totalSpace == 0 || (Double(usedSpace) / Double(totalSpace)) * 100.0 >= 90.0
}
private func availableDiskSpace() -> Int64? {
do {
return try URL(fileURLWithPath: NSHomeDirectory() as String).resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage
} catch {
Logger.module.error("Error Retrieving Disk Space: \(error.localizedDescription)")
}
return nil
}
private func totalDiskSpace() -> Int64? {
do {
if let result = try URL(fileURLWithPath: NSHomeDirectory() as String).resourceValues(forKeys: [.volumeTotalCapacityKey]).volumeTotalCapacity {
return Int64(result)
}
} catch {
Logger.module.error("Error Retrieving Disk Space: \(error.localizedDescription)")
}
return nil
}
}
extension PlaylistManager {
private func asset(for itemId: String, mediaSrc: String) -> AVURLAsset {
if let task = downloadManager.downloadTask(for: itemId) {
return task.asset
}
if let asset = downloadManager.localAsset(for: itemId) {
return asset
}
return AVURLAsset(url: URL(string: mediaSrc)!, options: AVAsset.defaultOptions)
}
}
extension PlaylistManager: PlaylistDownloadManagerDelegate {
func onDownloadProgressUpdate(id: String, percentComplete: Double) {
onDownloadProgressUpdate.send((id: id, percentComplete: percentComplete))
}
func onDownloadStateChanged(id: String, state: PlaylistDownloadManager.DownloadState, displayName: String?, error: Error?) {
onDownloadStateChanged.send((id: id, state: state, displayName: displayName, error: error))
}
}
extension PlaylistManager: NSFetchedResultsControllerDelegate {
public func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
onObjectChange.send((object: anObject, indexPath: indexPath, type: type, newIndexPath: newIndexPath))
}
public func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
onContentDidChange.send(())
}
public func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
onContentWillChange.send(())
}
}
extension PlaylistManager {
func getAssetDuration(item: PlaylistInfo, _ completion: @escaping (TimeInterval?) -> Void) {
if assetInformation.contains(where: { $0.itemId == item.tagId }) {
completion(nil)
return
}
fetchAssetDuration(item: item) { [weak self] duration in
guard let self = self else {
completion(nil)
return
}
if let index = self.assetInformation.firstIndex(where: { $0.itemId == item.tagId }) {
let assetFetcher = self.assetInformation.remove(at: index)
assetFetcher.cancelLoading()
}
completion(duration)
}
}
private func fetchAssetDuration(item: PlaylistInfo, _ completion: @escaping (TimeInterval?) -> Void) {
let tolerance: Double = 0.00001
let distance = abs(item.duration.distance(to: 0.0))
// If the database duration is live/indefinite
if item.duration.isInfinite || abs(item.duration.distance(to: TimeInterval.greatestFiniteMagnitude)) < tolerance {
completion(TimeInterval.infinity)
return
}
// If the database duration is 0.0
if distance >= tolerance {
// Return the database duration
completion(item.duration)
return
}
// Attempt to retrieve the duration from the Asset file
let asset: AVURLAsset
if item.src.isEmpty || item.pageSrc.isEmpty {
if let index = index(of: item.tagId), let urlAsset = assetAtIndex(index) {
asset = urlAsset
} else {
// Return the database duration
completion(item.duration)
return
}
} else {
asset = self.asset(for: item.tagId, mediaSrc: item.src)
}
// Accessing tracks blocks the main-thread if not already loaded
// So we first need to check the track status before attempting to access it!
var error: NSError?
let trackStatus = asset.statusOfValue(forKey: "tracks", error: &error)
if trackStatus == .loaded {
if !asset.tracks.isEmpty,
let track = asset.tracks(withMediaType: .video).first ?? asset.tracks(withMediaType: .audio).first {
if track.timeRange.duration.isIndefinite {
completion(TimeInterval.infinity)
} else {
completion(track.timeRange.duration.seconds)
}
return
}
}
// Accessing duration or commonMetadata blocks the main-thread if not already loaded
// So we first need to check the track status before attempting to access it!
let durationStatus = asset.statusOfValue(forKey: "duration", error: &error)
if durationStatus == .loaded {
// If it's live/indefinite
if asset.duration.isIndefinite {
completion(TimeInterval.infinity)
return
}
// If it's a valid duration
if abs(asset.duration.seconds.distance(to: 0.0)) >= tolerance {
completion(asset.duration.seconds)
return
}
}
switch Reach().connectionStatus() {
case .offline, .unknown:
completion(item.duration) // Return the database duration
return
case .online:
break
}
// We can't get the duration synchronously so we need to let the AVAsset load the media item
// and hopefully we get a valid duration from that.
DispatchQueue.global(qos: .userInitiated).async {
asset.loadValuesAsynchronously(forKeys: ["playable", "tracks", "duration"]) {
var error: NSError?
let trackStatus = asset.statusOfValue(forKey: "tracks", error: &error)
if let error = error {
Logger.module.error("AVAsset.statusOfValue error occurred: \(error.localizedDescription)")
}
let durationStatus = asset.statusOfValue(forKey: "tracks", error: &error)
if let error = error {
Logger.module.error("AVAsset.statusOfValue error occurred: \(error.localizedDescription)")
}
if trackStatus == .cancelled || durationStatus == .cancelled {
Logger.module.error("Asset Duration Fetch Cancelled")
ensureMainThread {
completion(nil)
}
return
}
if trackStatus == .failed && durationStatus == .failed, let error = error {
if error.code == NSURLErrorNoPermissionsToReadFile {
// Media item is expired.. permission is denied
Logger.module.debug("Playlist Media Item Expired: \(item.pageSrc)")
ensureMainThread {
completion(nil)
}
} else {
Logger.module.error("An unknown error occurred while attempting to fetch track and duration information: \(error.localizedDescription)")
ensureMainThread {
completion(nil)
}
}
return
}
var duration: CMTime = .zero
if trackStatus == .loaded {
if let track = asset.tracks(withMediaType: .video).first ?? asset.tracks(withMediaType: .audio).first {
duration = track.timeRange.duration
} else {
duration = asset.duration
}
} else if durationStatus == .loaded {
duration = asset.duration
}
ensureMainThread {
if duration.isIndefinite {
completion(TimeInterval.infinity)
} else if abs(duration.seconds.distance(to: 0.0)) > tolerance {
let newItem = PlaylistInfo(
name: item.name,
src: item.src,
pageSrc: item.pageSrc,
pageTitle: item.pageTitle,
mimeType: item.mimeType,
duration: duration.seconds,
lastPlayedOffset: 0.0,
detected: item.detected,
dateAdded: item.dateAdded,
tagId: item.tagId,
order: item.order,
isInvisible: item.isInvisible)
if PlaylistItem.itemExists(uuid: item.tagId) || PlaylistItem.itemExists(pageSrc: item.pageSrc) {
PlaylistItem.updateItem(newItem) {
completion(duration.seconds)
}
} else {
completion(duration.seconds)
}
} else {
completion(duration.seconds)
}
}
}
}
assetInformation.append(PlaylistAssetFetcher(itemId: item.tagId, asset: asset))
}
}
extension PlaylistManager {
@MainActor
static func syncSharedFolder(sharedFolderUrl: String) async throws {
guard let folder = PlaylistFolder.getSharedFolder(sharedFolderUrl: sharedFolderUrl),
let folderId = folder.uuid else {
return
}
let model = try await PlaylistSharedFolderNetwork.fetchPlaylist(folderUrl: sharedFolderUrl)
var oldItems = Set(folder.playlistItems?.map({ PlaylistInfo(item: $0) }) ?? [])
let deletedItems = oldItems.subtracting(model.mediaItems)
let newItems = Set(model.mediaItems).subtracting(oldItems)
oldItems = []
deletedItems.forEach({ PlaylistManager.shared.delete(item: $0) })
if !newItems.isEmpty {
await withCheckedContinuation { continuation in
PlaylistItem.updateItems(Array(newItems), folderUUID: folderId, newETag: model.eTag) {
continuation.resume()
}
}
}
}
@MainActor
static func syncSharedFolders() async throws {
let folderURLs = PlaylistFolder.getSharedFolders().compactMap({ $0.sharedFolderUrl })
await withTaskGroup(of: Void.self) { group in
folderURLs.forEach { url in
group.addTask {
try? await syncSharedFolder(sharedFolderUrl: url)
}
}
}
}
}
extension AVAsset {
func displayNames(for mediaSelection: AVMediaSelection) -> String? {
var names = ""
for mediaCharacteristic in availableMediaCharacteristicsWithMediaSelectionOptions {
guard let mediaSelectionGroup = mediaSelectionGroup(forMediaCharacteristic: mediaCharacteristic),
let option = mediaSelection.selectedMediaOption(in: mediaSelectionGroup)
else { continue }
if names.isEmpty {
names += " " + option.displayName
} else {
names += ", " + option.displayName
}
}
return names.isEmpty ? nil : names
}
}